package com.adley.oauth.resource.web;

import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.adley.oauth.resource.domain.Post;
import com.alibaba.fastjson.JSONObject;

@Controller
public class WeiboController {
    @RequestMapping("/blog/list")
    @PreAuthorize("#oauth2.hasAnyScope('read')")
    public ResponseEntity<List<Post>> getPostList() throws IOException {
        return new ResponseEntity(JSONObject.parseArray(String.join(",",Files.readAllLines(ResourceUtils.getFile("classpath:post/doc.json").toPath())),Post.class)
                                 .stream().map(p->new Post().setId(p.getId()).setTitle(p.getTitle())).collect(Collectors.toList()),HttpStatus.OK);
    }

    @RequestMapping("/blog/{id}")
    @PreAuthorize("#oauth2.hasAnyScope('read')")
    public ResponseEntity<Post> readPostContent(@PathVariable Long id, OAuth2Authentication auth) throws IOException {
        return new ResponseEntity(JSONObject.parseArray(String.join(",",Files.readAllLines(ResourceUtils.getFile("classpath:post/doc.json").toPath())),Post.class)
                                 .stream().filter(p->p.getId().equals(id)).findFirst().get(),HttpStatus.OK);
    }
}
